import json
import datetime
def getlastdata(obj,nowt):
    from pymongo import MongoClient as mc
    #client1 = mc("mongodb://ant:ant@localhost:27777/tick_f")
    client1 = mc("mongodb://ant:ant@121.199.56.237:27777/tick_f")
    tick=client1["tick_f"]
    t=tick[obj].find_one({"timekey":{"$lte":nowt}},sort=[("timekey",-1)])
    client1.close()
    return t
"""
tradeset_calender:交易日历表
#更新，
大连 ActionDay，郑商TradeDay，中金所的数量
毫秒字段=0 or 500;
增加timekey=ActionDay-updatetime;
增加增仓，现量开量，平量，性质，主卖/主买;涨幅涨速；
按交易所 是否夜盘规则处理：
TickDay:普通日盘：参数，obj,init,end 上海，大连，原油日盘，股票
TickSCnight:上海夜盘：参数：obj,init,end,mid  上海夜盘  原油夜盘
TickZCnight:obj,init,init1,end,nexttday 郑州夜盘
TickDCnight:obj,init,init1,end 大连夜盘
TickZCday:obj,init,end 郑州日盘
Tickflag:0:开盘集合竞价；1.连续竞价成交价；2.未成交报价变动；3.结算价；4.测试或是其他；5.收盘集合竞价
TT：TradeTime:sinit:集合申报开始；send：集合申报结束；ginit：连续竞价开始；gmid:连续盘中结束；gend：连续结束
"""
settlementPrice=1000000
timeday={}#商品日盘时间；上海，大连，郑州日盘品种用
timeday["sinit"]=datetime.time(8, 55, 0)
timeday["send"]=datetime.time(8, 59, 0)
timeday["ginit"]=datetime.time(9, 0, 0)
timeday["gend"]=datetime.time(15, 0, 1)
timenight1={}#夜盘1时间；大连，郑州夜盘品种用
timenight1["sinit"]=datetime.time(20, 55, 0)
timenight1["send"]=datetime.time(20, 59, 0)
timenight1["ginit"]=datetime.time(21, 0, 0)
timenight1["gmid"]=datetime.time(9, 0, 0)
timenight1["gend"]=datetime.time(15, 0, 1)
timenight2={}#夜盘2时间；上海夜盘品种用
timenight2["sinit"]=datetime.time(20, 55, 0)
timenight2["send"]=datetime.time(20, 59, 0)
timenight2["ginit"]=datetime.time(21, 0, 0)
timenight2["gmid1"]=datetime.time(2, 30, 1)
timenight2["gmid2"]=datetime.time(9, 0, 0)
timenight2["gend"]=datetime.time(15, 0, 1)
timecf1={}#中金所股指期货用
timecf1["sinit"]=datetime.time(9, 25, 0)
timecf1["send"]=datetime.time(9, 29, 0)
timecf1["ginit"]=datetime.time(9, 30, 0)
timecf1["gend"]=datetime.time(15, 0, 1)
timecf2={}#中金所国债期货用
timecf2["sinit"]=datetime.time(9, 10, 0)
timecf2["send"]=datetime.time(9, 14, 0)
timecf2["ginit"]=datetime.time(9, 15, 0)
timecf2["gend"]=datetime.time(15, 15, 1)
def gettickfeature(openvolume, closevolume, bsflag):
    if bsflag == 1:  # 买价成交；主卖；空方主动
        if openvolume > closevolume:  # 开仓 >  平仓
            if closevolume == 0:
                ff = 11  # 双开
            else:
                ff = 12  # 空开
        elif openvolume < closevolume:  # 开仓 <  平仓
            if openvolume == 0:
                ff = 13  # 双平
            else:
                ff = 14  # 空平
        else:  # 增仓为0
            ff = 15  # 空换
    elif bsflag == 2:  # 卖价成交；主买；多方主动
        if openvolume > closevolume:  # 开仓 >  平仓
            if closevolume == 0:
                ff = 21  # 双开
            else:
                ff = 22  # 多开
        elif openvolume < closevolume:  # 开仓 <  平仓
            if openvolume == 0:
                ff = 23  # 双平
            else:
                ff = 24  # 多平
        else:  # 增仓为0
            ff = 25  # 多换
    else:  # 其它
        ff = 31
    return ff
class TickDay:#sinit=datetime.time(8, 55, 0),send=datetime.time(8, 59, 0),sinit=datetime.time(9, 0, 0),gend=datetime.time(15, 0, 1)
    def __init__(self,obj,tradetime=timeday):
        self.obj = obj
        self.pretotalvolume = 0
        self.preopeninterest = 0
        self.isnewday = True
        self.pretime = ""
        self.tt=tradetime
        now = datetime.datetime.now()
        from jili.data.db import tradecal
        self.tradeday = tradecal.gettradeday(now.date())
        totime = now.time()
        if (totime >= self.tt["send"]) & (totime < self.tt["gend"]):
            self.getpredata(obj,now)
            print("read predata TickDay trade obj :" + obj)
    def getpredata(self,obj,now):
        t=getlastdata(obj,now)
        if t :
            print(t)
            tradingday = datetime.datetime.strptime(t["TradingDay"], '%Y%m%d').date()
            if (tradingday==self.tradeday):
                self.pretotalvolume = t["Volume"]
                self.preopeninterest = t["OpenInterest"]
                self.isnewday = False
                self.pretime = t["UpdateTime"]
                print(" pre datapretotalvolume :"+str(self.pretotalvolume)+" pre preopeninterest :"+str(self.preopeninterest)+  " pretime:"+self.pretime+" timekey:"+t["timekey"].strftime("%Y-%m-%d  %H:%M:%S.%f"))
    def calc(self,t):#对外计算接口
        tkey = t["ActionDay"] + " " + t["UpdateTime"] + "." + str(t["UpdateMillisec"])
        timekey = datetime.datetime.strptime(tkey, '%Y%m%d %H:%M:%S.%f')
        t["timekey"] = timekey
        totime = timekey.time()
        if (totime >= self.tt["send"]) & (totime < self.tt["gend"]):#盘中
            t["volume"] = t["Volume"] - self.pretotalvolume
            if t["volume"] == 0:  # 如果无成交行情不处理
                t["tickflag"] = 2
                t["deltainterest"] = 0
                t["totalvolume"] = t["Volume"]
                t["bsflag"] = 0
                t["dealfeatures"] = 0
                t["openvolume"] = 0
                t["closevolume"] = 0
            else:
                if (self.isnewday):# 开盘第一笔初始化与集合竞价标识
                    if (totime < self.tt["ginit"]):
                        t["tickflag"] = 0
                    else:
                        t["tickflag"] = 1
                    self.pretotalvolume = 0
                    self.preopeninterest = t["PreOpenInterest"]
                    self.isnewday = False
                else:
                    t["tickflag"] = 1
                t["deltainterest"] = t["OpenInterest"] - self.preopeninterest
                self.preopeninterest = t["OpenInterest"]
                t["totalvolume"] = t["Volume"]
                self.pretotalvolume = t["Volume"]
                openvolume = (t["volume"] + t["deltainterest"]) / 2
                closevolume = openvolume - t["deltainterest"]
                if t["LastPrice"] == t["AskPrice1"]:
                    bsflag = 1
                elif t["LastPrice"] == t["BidPrice1"]:
                    bsflag = 2
                else:
                    bsflag = 3
                t["bsflag"] = bsflag
                t["dealfeatures"] = gettickfeature(openvolume, closevolume, bsflag)
                t["openvolume"] = openvolume
                t["closevolume"] = closevolume
        else:
            if t["SettlementPrice"] < settlementPrice:
                t["tickflag"] = 3
            else:
                t["tickflag"] = 4
            t["deltainterest"] = 0
            t["totalvolume"] = t["Volume"]
            t["volume"] = 0
            t["bsflag"] = 0
            t["dealfeatures"] = 0
            t["openvolume"] = 0
            t["closevolume"] = 0
        return t
class TickSCnight:
    def __init__(self,obj,tradetime=timenight2):
        from jili.data.db import tradecal
        self.obj = obj
        self.pretotalvolume = 0
        self.preopeninterest = 0
        self.isnewday = True
        self.isnewday1 = False
        self.pretime = ""
        self.tt=tradetime
        now = datetime.datetime.now()
        totime = now.time()
        if (totime >= datetime.time(18, 0, 0)):
            self.tradeday = tradecal.gettradeday(now.date(),1)
        else:
            self.tradeday = tradecal.gettradeday(now.date())
        if (totime >= self.tt["send"]) | (totime < self.tt["gend"]):
            self.getpredata(obj,now)
            print("read predata is TickSCnight trade obj :" + obj)
    def getpredata(self,obj,now):
        t=getlastdata(obj,now)
        if t :
            print(t)
            tradingday = datetime.datetime.strptime(t["TradingDay"], '%Y%m%d').date()
            if (tradingday==self.tradeday):
                self.pretotalvolume = t["Volume"]
                self.preopeninterest = t["OpenInterest"]
                self.isnewday = False
                self.pretime = t["UpdateTime"]
                print(" pre datapretotalvolume :"+str(self.pretotalvolume)+" pre preopeninterest :"+str(self.preopeninterest)+  " pretime:"+self.pretime+" timekey:"+t["timekey"].strftime("%Y-%m-%d  %H:%M:%S.%f"))
            else:
                self.isnewday1 = True
                print("没有查找到，重新初始化第一笔行情")
    def calc(self,t):#对外计算接口
        tkey = t["ActionDay"] + " " + t["UpdateTime"] + "." + str(t["UpdateMillisec"])
        timekey = datetime.datetime.strptime(tkey, '%Y%m%d %H:%M:%S.%f')
        t["timekey"] = timekey
        totime = timekey.time()
        if ((totime < self.tt["gend"]) & (totime >= self.tt["gmid2"])):
            t["volume"] = t["Volume"] - self.pretotalvolume
            if t["volume"] == 0:  # 如果无成交行情不处理
                t["tickflag"] = 2
                t["deltainterest"] = 0
                t["totalvolume"] = t["Volume"]
                t["bsflag"] = 0
                t["dealfeatures"] = 0
                t["openvolume"] = 0
                t["closevolume"] = 0
            else:
                if (self.isnewday1):# 开盘第一笔初始化与集合竞价标识
                    self.pretotalvolume = 0
                    self.preopeninterest = t["PreOpenInterest"]
                    self.isnewday1 = False
                t["tickflag"] = 1
                t["deltainterest"] = t["OpenInterest"] - self.preopeninterest
                self.preopeninterest = t["OpenInterest"]
                t["totalvolume"] = t["Volume"]
                self.pretotalvolume = t["Volume"]
                openvolume = (t["volume"] + t["deltainterest"]) / 2
                closevolume = openvolume - t["deltainterest"]
                if t["LastPrice"] == t["AskPrice1"]:
                    bsflag = 1
                elif t["LastPrice"] == t["BidPrice1"]:
                    bsflag = 2
                else:
                    bsflag = 3
                t["bsflag"] = bsflag
                t["dealfeatures"] = gettickfeature(openvolume, closevolume, bsflag)
                t["openvolume"] = openvolume
                t["closevolume"] = closevolume
        elif (totime >= self.tt["send"]) | (totime < self.tt["gmid1"]):#夜盘
            t["volume"] = t["Volume"] - self.pretotalvolume
            if t["volume"] == 0:  # 如果无成交行情不处理
                t["tickflag"] = 2
                t["deltainterest"] = 0
                t["totalvolume"] = t["Volume"]
                t["bsflag"] = 0
                t["dealfeatures"] = 0
                t["openvolume"] = 0
                t["closevolume"] = 0
            else:
                if (self.isnewday):# 开盘第一笔初始化与集合竞价标识
                    if (totime < self.tt["ginit"]):
                        t["tickflag"] = 0
                    else:
                        t["tickflag"] = 1
                    self.pretotalvolume = 0
                    self.preopeninterest = t["PreOpenInterest"]
                    self.isnewday = False
                else:
                    t["tickflag"] = 1
                t["deltainterest"] = t["OpenInterest"] - self.preopeninterest
                self.preopeninterest = t["OpenInterest"]
                t["totalvolume"] = t["Volume"]
                self.pretotalvolume = t["Volume"]
                openvolume = (t["volume"] + t["deltainterest"]) / 2
                closevolume = openvolume - t["deltainterest"]
                if t["LastPrice"] == t["AskPrice1"]:
                    bsflag = 1
                elif t["LastPrice"] == t["BidPrice1"]:
                    bsflag = 2
                else:
                    bsflag = 3
                t["bsflag"] = bsflag
                t["dealfeatures"] = gettickfeature(openvolume, closevolume, bsflag)
                t["openvolume"] = openvolume
                t["closevolume"] = closevolume
        else:
            if t["SettlementPrice"] < settlementPrice:
                t["tickflag"] = 3
            else:
                t["tickflag"] = 4
            t["deltainterest"] = 0
            t["totalvolume"] = t["Volume"]
            t["volume"] = 0
            t["bsflag"] = 0
            t["dealfeatures"] = 0
            t["openvolume"] = 0
            t["closevolume"] = 0
        return t
class TickDCnight:
    def __init__(self,obj,tradetime=timenight1):
        from jili.data.db import tradecal
        self.obj = obj
        self.pretotalvolume = 0
        self.preopeninterest = 0
        self.isnewday = True
        self.isnewday1 = False
        self.pretime = ""
        self.tt=tradetime
        now = datetime.datetime.now()
        totime = now.time()
        if (totime >= datetime.time(18, 0, 0)):
            self.tradeday = tradecal.gettradeday(now.date(),1)
        else:
            self.tradeday = tradecal.gettradeday(now.date())
        if (totime >= self.tt["send"]) | (totime < self.tt["gend"]):
            self.getpredata(obj,now)
            print("read predata is TickDCnight trade obj :" + obj)
    def getpredata(self,obj,now):
        t=getlastdata(obj,now)
        if t :
            print(t)
            tradingday = datetime.datetime.strptime(t["TradingDay"], '%Y%m%d').date()
            if (tradingday==self.tradeday):
                self.pretotalvolume = t["Volume"]
                self.preopeninterest = t["OpenInterest"]
                self.isnewday = False
                self.pretime = t["UpdateTime"]
                print(" pre datapretotalvolume :"+str(self.pretotalvolume)+" pre preopeninterest :"+str(self.preopeninterest)+  " pretime:"+self.pretime+" timekey:"+t["timekey"].strftime("%Y-%m-%d  %H:%M:%S.%f"))
            else:
                self.isnewday1 = True 
                print("没有查找到，重新初始化第一笔行情")
    def calc(self,t):#对外计算接口
        recvdate = t["RecvTimeStamp"].strftime("%Y%m%d")  # 接收日期，用来填补大连的ActionDay
        tkey = t["ActionDay"] + " " + t["UpdateTime"] + "." + str(t["UpdateMillisec"])
        timekey = datetime.datetime.strptime(tkey, '%Y%m%d %H:%M:%S.%f')
        t["timekey"] = timekey
        totime = timekey.time()
        if ((totime < self.tt["gend"]) & (totime >= self.tt["gmid"])):
            t["volume"] = t["Volume"] - self.pretotalvolume
            if t["volume"] == 0:  # 如果无成交行情不处理
                t["tickflag"] = 2
                t["deltainterest"] = 0
                t["totalvolume"] = t["Volume"]
                t["bsflag"] = 0
                t["dealfeatures"] = 0
                t["openvolume"] = 0
                t["closevolume"] = 0
            else:
                if (self.isnewday1):# 开盘第一笔初始化与集合竞价标识
                    self.pretotalvolume = 0
                    self.preopeninterest = t["PreOpenInterest"]
                    self.isnewday1 = False
                t["tickflag"] = 1
                t["deltainterest"] = t["OpenInterest"] - self.preopeninterest
                self.preopeninterest = t["OpenInterest"]
                t["totalvolume"] = t["Volume"]
                self.pretotalvolume = t["Volume"]
                openvolume = (t["volume"] + t["deltainterest"]) / 2
                closevolume = openvolume - t["deltainterest"]
                if t["LastPrice"] == t["AskPrice1"]:
                    bsflag = 1
                elif t["LastPrice"] == t["BidPrice1"]:
                    bsflag = 2
                else:
                    bsflag = 3
                t["bsflag"] = bsflag
                t["dealfeatures"] = gettickfeature(openvolume, closevolume, bsflag)
                t["openvolume"] = openvolume
                t["closevolume"] = closevolume
        elif (totime >= self.tt["send"]):#夜盘
            t["ActionDay"] = recvdate
            tkey = t["ActionDay"] + " " + t["UpdateTime"] + "." + str(t["UpdateMillisec"])
            timekey = datetime.datetime.strptime(tkey, '%Y%m%d %H:%M:%S.%f')
            t["timekey"] = timekey
            t["volume"] = t["Volume"] - self.pretotalvolume
            if t["volume"] == 0:  # 如果无成交行情不处理
                t["tickflag"] = 2
                t["deltainterest"] = 0
                t["totalvolume"] = t["Volume"]
                t["bsflag"] = 0
                t["dealfeatures"] = 0
                t["openvolume"] = 0
                t["closevolume"] = 0
            else:
                if (self.isnewday):# 开盘第一笔初始化与集合竞价标识
                    if (totime < self.tt["ginit"]):
                        t["tickflag"] = 0
                    else:
                        t["tickflag"] = 1
                    self.pretotalvolume = 0
                    self.preopeninterest = t["PreOpenInterest"]
                    self.isnewday = False
                else:
                    t["tickflag"] = 1
                t["deltainterest"] = t["OpenInterest"] - self.preopeninterest
                self.preopeninterest = t["OpenInterest"]
                t["totalvolume"] = t["Volume"]
                self.pretotalvolume = t["Volume"]
                openvolume = (t["volume"] + t["deltainterest"]) / 2
                closevolume = openvolume - t["deltainterest"]
                if t["LastPrice"] == t["AskPrice1"]:
                    bsflag = 1
                elif t["LastPrice"] == t["BidPrice1"]:
                    bsflag = 2
                else:
                    bsflag = 3
                t["bsflag"] = bsflag
                t["dealfeatures"] = gettickfeature(openvolume, closevolume, bsflag)
                t["openvolume"] = openvolume
                t["closevolume"] = closevolume
        else:
            t["ActionDay"] = recvdate
            tkey = t["ActionDay"] + " " + t["UpdateTime"] + "." + str(t["UpdateMillisec"])
            timekey = datetime.datetime.strptime(tkey, '%Y%m%d %H:%M:%S.%f')
            t["timekey"] = timekey
            if t["SettlementPrice"] < settlementPrice:
                t["tickflag"] = 3
            else:
                t["tickflag"] = 4
            t["deltainterest"] = 0
            t["deltainterest"] = 0
            t["totalvolume"] = t["Volume"]
            t["volume"] = 0
            t["bsflag"] = 0
            t["dealfeatures"] = 0
            t["openvolume"] = 0
            t["closevolume"] = 0
        return t
class TickZCnight:
    def __init__(self,obj,tradetime=timenight1):
        from jili.data.db import tradecal
        self.obj = obj
        self.pretotalvolume = 0
        self.preopeninterest = 0
        self.isnewday = True
        self.isnewday1 = False
        self.pretime = ""
        self.tt=tradetime
        now = datetime.datetime.now()
        totime = now.time()
        if (totime >= datetime.time(18, 0, 0)):
            self.tradeday = tradecal.gettradeday(now.date(),1)
        else:
            self.tradeday = tradecal.gettradeday(now.date())
        if (totime >= self.tt["send"]) | (totime < self.tt["gend"]):
            self.getpredata(obj,now)
            print("read predata isnight trade obj :" + obj)
    def getpredata(self,obj,now):
        t=getlastdata(obj,now)
        if t :
            print(t)
            tradingday = datetime.datetime.strptime(t["TradingDay"], '%Y%m%d').date()
            if (tradingday==self.tradeday):
                self.pretotalvolume = t["Volume"]
                self.preopeninterest = t["OpenInterest"]
                self.isnewday = False
                self.pretime = t["UpdateTime"]
                print(" pre datapretotalvolume :"+str(self.pretotalvolume)+" pre preopeninterest :"+str(self.preopeninterest)+  " pretime:"+self.pretime+" timekey:"+t["timekey"].strftime("%Y-%m-%d  %H:%M:%S.%f"))
            else:
                self.isnewday1 = True
                print("没有查找到，重新初始化第一笔行情")
    def calc(self,t):#对外计算接口
        if self.pretime != t["UpdateTime"]:  # 修复毫秒默认0；相同500
            tkey = t["ActionDay"] + " " + t["UpdateTime"] + "." + str(t["UpdateMillisec"])
        else:
            tkey = t["ActionDay"] + " " + t["UpdateTime"] + ".500"
            t["UpdateMillisec"] = 500
        self.pretime = t["UpdateTime"]
        timekey = datetime.datetime.strptime(tkey, '%Y%m%d %H:%M:%S.%f')
        t["timekey"] = timekey
        totime = timekey.time()
        if totime < datetime.time(18, 0, 0):  # 18点前为日盘；23点结束
            if (totime < self.tt["gend"]) & (totime >= self.tt["gmid"]):
                t["volume"] = t["Volume"] - self.pretotalvolume
                if t["volume"] == 0:  # 如果无成交行情不处理
                    t["tickflag"] = 2
                    t["deltainterest"] = 0
                    t["totalvolume"] = t["Volume"]
                    t["volume"] = 0
                    t["bsflag"] = 0
                    t["dealfeatures"] = 0
                    t["openvolume"] = 0
                    t["closevolume"] = 0
                else:
                    if (self.isnewday1):# 开盘第一笔初始化与集合竞价标识
                        self.pretotalvolume = 0
                        self.preopeninterest = t["PreOpenInterest"]
                        self.isnewday1 = False
                    t["tickflag"] = 1
                    t["deltainterest"] = t["OpenInterest"] - self.preopeninterest
                    self.preopeninterest = t["OpenInterest"]
                    t["totalvolume"] = t["Volume"]
                    self.pretotalvolume = t["Volume"]
                    openvolume = (t["volume"] + t["deltainterest"]) / 2
                    closevolume = openvolume - t["deltainterest"]
                    if t["LastPrice"] == t["AskPrice1"]:
                        bsflag = 1
                    elif t["LastPrice"] == t["BidPrice1"]:
                        bsflag = 2
                    else:
                        bsflag = 3
                    t["bsflag"] = bsflag
                    t["dealfeatures"] = gettickfeature(openvolume, closevolume, bsflag)
                    t["openvolume"] = openvolume
                    t["closevolume"] = closevolume
            else:
                if t["SettlementPrice"] < settlementPrice:
                    t["tickflag"] = 3
                else:
                    t["tickflag"] = 4
                t["deltainterest"] = 0
                t["totalvolume"] = t["Volume"]
                t["volume"] = 0
                t["bsflag"] = 0
                t["dealfeatures"] = 0
                t["openvolume"] = 0
                t["closevolume"] = 0
        else:  # 第二天、修改交易日
            tradeday = self.tradeday
            t["TradingDay"] = tradeday.strftime("%Y%m%d")
            if totime >= self.tt["send"]:#盘中
                t["volume"] = t["Volume"] - self.pretotalvolume
                if t["volume"] == 0:  # 如果无成交行情不处理
                    t["tickflag"] = 2
                    t["deltainterest"] = 0
                    t["totalvolume"] = t["Volume"]
                    t["volume"] = 0
                    t["bsflag"] = 0
                    t["dealfeatures"] = 0
                    t["openvolume"] = 0
                    t["closevolume"] = 0
                else:
                    if (self.isnewday):# 开盘第一笔初始化与集合竞价标识
                        if (totime < self.tt["ginit"]):
                            t["tickflag"] = 0
                        else:
                            t["tickflag"] = 1
                        self.pretotalvolume = 0
                        self.preopeninterest = t["PreOpenInterest"]
                        self.isnewday = False
                    else:
                        t["tickflag"] = 1
                    t["deltainterest"] = t["OpenInterest"] - self.preopeninterest
                    self.preopeninterest = t["OpenInterest"]
                    t["totalvolume"] = t["Volume"]
                    self.pretotalvolume = t["Volume"]
                    openvolume = (t["volume"] + t["deltainterest"]) / 2
                    closevolume = openvolume - t["deltainterest"]
                    if t["LastPrice"] == t["AskPrice1"]:
                        bsflag = 1
                    elif t["LastPrice"] == t["BidPrice1"]:
                        bsflag = 2
                    else:
                        bsflag = 3
                    t["bsflag"] = bsflag
                    t["dealfeatures"] = gettickfeature(openvolume, closevolume, bsflag)
                    t["openvolume"] = openvolume
                    t["closevolume"] = closevolume
            else:#盘前有5分钟集合竞价
                t["tickflag"] = 4
                t["deltainterest"] = 0
                t["totalvolume"] = t["Volume"]
                t["volume"] = 0
                t["bsflag"] = 0
                t["dealfeatures"] = 0
                t["openvolume"] = 0
                t["closevolume"] = 0
        return t
class TickZCday:
    def __init__(self,obj,tradetime=timeday):
        from jili.data.db import tradecal
        self.obj = obj
        self.pretotalvolume = 0
        self.preopeninterest = 0
        self.isnewday = True
        self.pretime = ""
        self.tt=tradetime
        now = datetime.datetime.now()
        self.tradeday = tradecal.gettradeday(now.date())
        totime = now.time()
        if (totime >= self.tt["send"]) & (totime < self.tt["gend"]):
            self.getpredata(obj,now)
            print("read predata TickZCDay trade obj :" + obj)
    def getpredata(self,obj,now):
        t=getlastdata(obj,now)
        if t :
            print(t)
            tradingday = datetime.datetime.strptime(t["TradingDay"], '%Y%m%d').date()
            if (tradingday==self.tradeday):
                self.pretotalvolume = t["Volume"]
                self.preopeninterest = t["OpenInterest"]
                self.isnewday = False
                self.pretime = t["UpdateTime"]
                print(" pre datapretotalvolume :"+str(self.pretotalvolume)+" pre preopeninterest :"+str(self.preopeninterest)+  " pretime:"+self.pretime+" timekey:"+t["timekey"].strftime("%Y-%m-%d  %H:%M:%S.%f"))
    def calc(self,t):#对外计算接口
        if self.pretime != t["UpdateTime"]:  # 修复毫秒默认0；相同500
            tkey = t["ActionDay"] + " " + t["UpdateTime"] + "." + str(t["UpdateMillisec"])
        else:
            tkey = t["ActionDay"] + " " + t["UpdateTime"] + ".500"
            t["UpdateMillisec"] = 500
        self.pretime = t["UpdateTime"]
        timekey = datetime.datetime.strptime(tkey, '%Y%m%d %H:%M:%S.%f')
        t["timekey"] = timekey
        totime = timekey.time()
        if (totime >= self.tt["send"]) & (totime < self.tt["gend"]):#盘中
            t["volume"] = t["Volume"] - self.pretotalvolume
            if t["volume"] == 0:  # 如果无成交行情不处理
                t["tickflag"] = 2
                t["deltainterest"] = 0
                t["totalvolume"] = t["Volume"]
                t["bsflag"] = 0
                t["dealfeatures"] = 0
                t["openvolume"] = 0
                t["closevolume"] = 0
            else:
                if (self.isnewday):# 开盘第一笔初始化与集合竞价标识
                    if (totime < self.tt["ginit"]):
                        t["tickflag"] = 0
                    else:
                        t["tickflag"] = 1
                    self.pretotalvolume = 0
                    self.preopeninterest = t["PreOpenInterest"]
                    self.isnewday = False
                else:
                    t["tickflag"] = 1
                t["deltainterest"] = t["OpenInterest"] - self.preopeninterest
                self.preopeninterest = t["OpenInterest"]
                t["totalvolume"] = t["Volume"]
                self.pretotalvolume = t["Volume"]
                openvolume = (t["volume"] + t["deltainterest"]) / 2
                closevolume = openvolume - t["deltainterest"]
                if t["LastPrice"] == t["AskPrice1"]:
                    bsflag = 1
                elif t["LastPrice"] == t["BidPrice1"]:
                    bsflag = 2
                else:
                    bsflag = 3
                t["bsflag"] = bsflag
                t["dealfeatures"] = gettickfeature(openvolume, closevolume, bsflag)
                t["openvolume"] = openvolume
                t["closevolume"] = closevolume
        else:
            if t["SettlementPrice"] < settlementPrice:
                t["tickflag"] = 3
            else:
                t["tickflag"] = 4
            t["deltainterest"] = 0
            t["totalvolume"] = t["Volume"]
            t["volume"] = 0
            t["bsflag"] = 0
            t["dealfeatures"] = 0
            t["openvolume"] = 0
            t["closevolume"] = 0
        return t
#------------------------------------init ticks calor--------------------------
tickdeals={}
def gettickdeal(obj):
    from jili.data.obj import isnighttrade as isnightobj,getmarketcode
    if obj in tickdeals.keys():
        return tickdeals[obj]
    else:
        mkcode = getmarketcode(obj)
        log = "mkcode:"+mkcode+" obj:"+obj
        if (mkcode == "XZCE") | (mkcode == "CZC")|(mkcode=="CZCE"):  # 郑州CZC  XZCE
            if isnightobj(obj):
                t=TickZCnight(obj)
                log = log+" TickZCnight"
            else:
                t=TickZCday(obj)#毫秒\
                log = log+" TickZCday"
        elif (mkcode == "XDCE") | (mkcode == "DCE"):  # 大连 DCE  XDCE
            if isnightobj(obj):
                t=TickDCnight(obj)
                log = log+" TickDCnight"
            else:
                t=TickDay(obj)
                log = log+" TickDay"
        elif (mkcode == "XSGE") | (mkcode == "SHF")|(mkcode=="SHFE"):  # SHF XSGE
            if isnightobj(obj):
                t=TickSCnight(obj)
                log = log+" TickSCnight"
            else:
                t=TickDay(obj)
                log = log+" TickDay"
        elif (mkcode == "CCFX") | (mkcode == "CFE")|(mkcode=="CFFEX"):  # CCFX CFE
            pcode=obj[:-4]
            if (obj[0]=="T"):#国债期货类
                t= TickDay(obj,timecf2)#交易时间不一样
                log = log+" TickCFDay timecf2 pcode:"+pcode
            else:#其它期货类
                t= TickDay(obj,timecf1)#交易时间不一样
                log = log+" TickCFDay timecf1 pcode:"+pcode
        elif mkcode=="INE":
            if isnightobj(obj):
                t=TickSCnight(obj)
                log = log+" TickSCnight"
            else:
                t=TickDay(obj)
                log = log+" TickDay"
        else:# 不能处理的代码
            print("un deal obj :" + obj+" mkcode: "+mkcode)
        tickdeals[obj]=t
        return t